import React, { Component } from "react";
import axios from "axios";
import PubSub from "pubsub-js";

class AuthorsArea extends Component {
  // 1.分析组件状态,
  //1.1 一开始提示状态
  //1.2 搜索中状态
  //1.3 搜索结果出来的状态
  //1.4 和搜索失败的状态
  state = {
    //请输入作者的文本
    initView: true,
    //点击搜索后,显示搜索中文本
    loading: false,
    //搜索完得到list
    users: null,
    //如果搜索出错了
    errorMsg: null,
  };
  // 一上来就待订阅消息(相当于绑定和监听)
  componentDidMount() {
    // 订阅消息(msg=='发布消息的名字key就是 search');而data才是数据
    PubSub.subscribe("search", (msg, searchName) => {
      this.setState({
        loading: true,
        initView: false,
      });
      let url = `https://api.github.com/search/users?q=${searchName}`;
      axios
        .get(url)
        .then((res) => {
          //得到响应数据
          const reult = res.data;
          const users = reult.items.map((item, index) => ({
            name: item.login,
            url: item.html_url,
            avatarUrl: item.avatar_url,
          }));
          //更新状态
          this.setState({
            loading: false,
            users,
          });
        })
        .catch((error) => {
          //更新失败的状态
          this.setState({
            errorMsg: error.message,
            loading: false,
          });
        });
    });
  }
  // componentWillUnmount() {
  //   PubSub.unsubscribe("search");
  // }
  render() {
    const { initView, loading, users, errorMsg } = this.state;
    if (initView) {
      return <h2>请输入关键字进行搜索</h2>;
    } else if (loading) {
      return <h2>正在搜索中....</h2>;
    } else if (errorMsg) {
      return <h2>{errorMsg}</h2>;
    } else {
      return (
        <div className="row">
          {users.map((user, index) => (
            <div
              className="card"
              key={index}
              style={{
                width: "100px",
                display: "inline-block",
                margin: "10px 10px",
              }}
            >
              <a href={user.url} target="_brank">
                <img
                  src={user.avatarUrl}
                  alt="用户头像"
                  style={{ width: 100 }}
                />
              </a>
              <p className="card-text">{user.name}</p>
            </div>
          ))}
        </div>
      );
    }
  }
}

export default AuthorsArea;
